package sms

import (
	"fmt"
	"longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/http"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/redis/cache"
)

//opt 通道 https://docs.fast2sms.com/#overview

func newOtp() (SMS, error) {
	configPri := cache.GetConfigPri()
	url := "https://www.fast2sms.com/dev/bulkV2"
	return &otp{url: url, authKey: configPri.IhuyiApikey}, nil
}

type otp struct {
	url     string
	authKey string
}

func (o *otp) Name() string {
	return "opt-sms"
}

func (o *otp) SendCode(areaCode string, phoneNumber string, verifyCode string) error {
	header := make(map[string]string)
	header["authorization"] = o.authKey
	payload := []byte(fmt.Sprintf("variables_values=%s&route=otp&numbers=%s", verifyCode, phoneNumber))
	rs, err := http.HttpHParaPost(o.url, header, string(payload), _const.CONN_TIMEOUT_MS, _const.SERVE_TIMEOUT_MS)
	if err != nil {
		global.Log.Errorf("opt sms SendCode err:%v", err)
		//return errors.New("opt sms SendCode err")
		return nil
	}
	resp := &Resp{}
	err = util.Json2Struct(string(rs), &resp)
	if err != nil {
		return err
	}
	if !resp.Return {
		global.Log.Errorf("SendCode resp:%+v,rs:%v", resp, string(rs))
		//return errors.New("opt sms SendCode err")
	}
	return nil
}

type Resp struct {
	StatusCode string `json:"status_code"`
	//Message    string `json:"message"`
	Return bool `json:"return"`
}
